package com.yingwei.${pojo.getMetaAsString("project_name")}.swing;

<#assign hasSet = false >

<#foreach field in pojo.getAllPropertiesIterator()>
<#if pojo.getJavaTypeName(field,false).equals("Set")>
	<#assign hasSet = true >
	<#assign SetClassName = pojo.beanCapitalize(field.name) >
	<#assign field1 = field >
</#if>
</#foreach>

<#if !hasSet>
public class ${pojo.getDeclarationName()}CrossEdit {}

<#else>
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yingwei.${pojo.getMetaAsString("project_name")}.control.Data;
import com.yingwei.${pojo.getMetaAsString("project_name")}.model.businessobject.${pojo.getDeclarationName()};
import com.yingwei.${pojo.getMetaAsString("project_name")}.model.businessobject.${SetClassName};

@SuppressWarnings("serial")
/**
 * This class needs to access message bundle properties:
 * add_new_${pojo.getDeclarationName()}, delete_${pojo.getDeclarationName()}, refresh_${pojo.getDeclarationName()}
 * ${pojo.getDeclarationName()}_management
 * 
 */
public class ${pojo.getDeclarationName()}CrossEdit extends JPanel
{
    private static Logger logger = LoggerFactory.getLogger(${pojo.getDeclarationName()}CrossEdit.class);
    private static Locale currentLocale = Locale.CHINA;
    private static ResourceBundle bundle = ResourceBundle.getBundle("MessagesBundle", Locale.CHINA);
    Data data = new Data();
	${SetClassName} crossObject;

    public ${pojo.getDeclarationName()}CrossEdit( ${SetClassName} crossObject1 )
    {
		super(new BorderLayout());
		setPreferredSize(new Dimension(1200, 800));
		
		crossObject = crossObject1;
		data.init();

		final MyTableModel myModel = new MyTableModel();
		final JTable table = new JTable(myModel);
		table.setRowSorter(new TableRowSorter<TableModel>(myModel));
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		setUpEditColumn(table);

		JPanel p = new JPanel(new FlowLayout());
	
		Object[] messageArguments = {
			crossObject.getName()	
		};
		MessageFormat formatter = new MessageFormat("");
		formatter.setLocale(currentLocale);
		formatter.applyPattern(bundle.getString("which_${SetClassName}_button"));
		String output = formatter.format(messageArguments);		
		JButton okButton = new JButton(output);
	
		p.add(okButton);

		JScrollPane scroller = new JScrollPane();
		scroller.setViewportView(table);
		scroller.setViewportBorder(BorderFactory.createLineBorder(Color.black));
		add(scroller, BorderLayout.CENTER);
		add(p, BorderLayout.SOUTH);
		okButton.addActionListener(new ActionListener()
		{
	    	public void actionPerformed(ActionEvent ae)
		    {
				TopLevel.frame.getGlassPane().setVisible(false);
		    }
		});
	}

    public void setUpEditColumn(JTable table)
    {
		// DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		// renderer.setToolTipText(bundle.getString("click_to_edit"));
    }

    class MyTableModel extends AbstractTableModel
    {
		private String[] columnNames = {
"${SetClassName}",
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
"${field.name}"<#if field_has_next >,
</#if> 
</#if> 
</#foreach>			 
		};
	
		public int getColumnCount()
		{
		    return columnNames.length;
		}
	
		public int getRowCount()
		{
		    return data.get${pojo.getDeclarationName()}s().size();
		}

		public String getColumnName(int col)
		{
		    return columnNames[col];
		}
	
		public Object getValueAt(int row, int col)
		{
		    ${pojo.getDeclarationName()} value = data.get${pojo.getDeclarationName()}s().get(row);
		    switch (col)
		    {
				case 0:
					for( ${pojo.getDeclarationName()} val : crossObject.get${pojo.getDeclarationName()}() )
				    {
						if( value.getId() == val.getId() )
						{
				    	    return new Boolean(true);
				    	}
				    }
				    return new Boolean(false);
<#assign x = 1> 			
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
				case ${x}:
					return value.${pojo.getGetterSignature(field)}();
<#assign x = x+1> 			
</#if> 
</#foreach>			 
		    }
		    return null;
		}

	/*
	 * JTable uses this method to determine the default renderer/ editor for
	 * each cell.
	 */
	@SuppressWarnings("unchecked")
	public Class getColumnClass(int c)
	{
	    switch (c)
	    {
	    	case 0:
	    		return Boolean.class;
<#assign x = 1> 			
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
			case ${x}:
			<#if pojo.getJavaTypeName(field, false).equals("long") >
				return Long.class; 
			<#else>	
				return ${pojo.getJavaTypeName(field, false)}.class;
			</#if> 
<#assign x = x+1> 			
</#if> 
</#foreach>			 
	    }
	    return Integer.class;
	}

	/*
	 * Don't need to implement this method unless your table's editable.
	 */
	public boolean isCellEditable(int row, int col)
	{
		switch (col)
		{
			case 0:
				return true; 
<#assign x = 1> 			
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
			case ${x}:
			<#if pojo.getFieldDescription(field).indexOf("editable") != -1 >
				return true; 
			<#else>	
				return false;
			</#if> 
<#assign x = x+1> 			
</#if> 
</#foreach>			 
		}
		return false;
	}

	/*
	 * Don't need to implement this method unless your table's data can
	 * change.
	 */
	public void setValueAt(Object value, int row, int col)
	{
	    try
	    {
			${pojo.getDeclarationName()} obj = data.get${pojo.getDeclarationName()}s().get(row);
			switch (col)
			{
				case 0:
				    if( ((Boolean)value).booleanValue() )
				    {
						crossObject.get${pojo.getDeclarationName()}().add( obj );
						//obj.get${SetClassName}().add(crossObject);
				    }
				    else
				    {
						crossObject.get${pojo.getDeclarationName()}().remove( obj );
						//obj.get${SetClassName}().remove(crossObject);
				    }
				    break;
<#assign x = 1>
<#foreach field in pojo.getAllPropertiesIterator()>
<#if !pojo.getJavaTypeName(field,false).equals("Set") >
			<#if pojo.getFieldDescription(field).indexOf("editable") != -1 >
				case ${x}:
				<#if pojo.getJavaTypeName(field,false).equals("String") >
					obj.set${pojo.getPropertyName(field)}( (String)value );
				</#if> 
				<#if pojo.getJavaTypeName(field,false).equals("long") >
					obj.set${pojo.getPropertyName(field)}( new Long(value.toString()) );
				</#if> 
				<#if pojo.getJavaTypeName(field,false).equals("Date") >
					obj.set${pojo.getPropertyName(field)}( (Date)value );
				</#if> 
				<#if pojo.getJavaTypeName(field,false).equals("Boolean") >
					obj.set${pojo.getPropertyName(field)}( (Boolean)value );
				</#if> 
				<#if pojo.getJavaTypeName(field,false).equals("Long") >
					obj.set${pojo.getPropertyName(field)}( (Long)value );
				</#if> 
				<#if (field.type.toString().indexOf("ManyToOneType")>0) >
					obj.set${pojo.getPropertyName(field)}( (${pojo.getJavaTypeName(field,false)})value );
				</#if> 
					break;
			</#if>
				//${pojo.getJavaTypeName(field,false)}
<#assign x = x+1>
</#if> 
</#foreach>			 
				}
				data.flush();
		    }
		    catch (Exception e)
		    {
		    	e.printStackTrace();
				JOptionPane.showMessageDialog(null, bundle.getString("please_input")+e.getMessage());
		    }
		}
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI()
    {
		// Create and set up the window.
		JFrame frame = new JFrame(bundle.getString("${SetClassName}_management"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		Data data = new Data();
		data.init();
		${SetClassName} sc = data.get${SetClassName}s().get(0);
		// Create and set up the content pane.
		${pojo.getDeclarationName()}CrossEdit newContentPane = new ${pojo.getDeclarationName()}CrossEdit(sc);
		newContentPane.setOpaque(true); // content panes must be opaque
		frame.setContentPane(newContentPane);
	
		// Display the window.
		frame.pack();
		frame.setVisible(true);
    }
	
    public static void main(String[] args)
    {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				// read from file MessagesBundle_en_us.properties
				bundle = ResourceBundle.getBundle("MessagesBundle", Locale.CHINA);
				System.out.println("Message in " + Locale.US + ": " + bundle.getString("greeting"));		
				createAndShowGUI();
			}
		});
	}
}

</#if>